<template>
  <a-drawer :title="title" :width="800" placement="right" :closable="true" @close="close" :visible="visible">
    <a-spin :spinning="confirmLoading">
      <a-descriptions :title="outbound.outboundNo" bordered :column="3">
        <a-descriptions-item label="出库类型">
          <j-dict-tag v-if="outbound.outboundType" :value="outbound.outboundType" dictCode="wms_outbound_type" />
          <span v-else>-</span>
        </a-descriptions-item>
        <a-descriptions-item label="出库日期">
          {{ outbound.outboundDate }}
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <j-dict-tag v-if="outbound.status" :value="outbound.status" dictCode="wms_outbound_status" />
          <span v-else>-</span>
        </a-descriptions-item>
        <a-descriptions-item label="关联订单号" v-if="outbound.orderNo">
          {{ outbound.orderNo }}
        </a-descriptions-item>
        <a-descriptions-item label="关联领料单号" :span="2" v-if="outbound.requisitionNo">
          {{ outbound.requisitionNo }}
        </a-descriptions-item>
        <a-descriptions-item label="备注" :span="3">
          {{ outbound.remark }}
        </a-descriptions-item>
      </a-descriptions>

      <!-- 明细信息 -->
      <a-divider orientation="left">明细信息</a-divider>
      <a-collapse v-if="outbound.outboundDetailList && outbound.outboundDetailList.length > 0" :bordered="false">
        <a-collapse-panel
          v-for="(detail, index) in outbound.outboundDetailList"
          :key="index"
          :header="getMaterialHeader(detail)"
        >
          <template slot="extra">
            <a-tag :color="getDetailStatusColor(detail.allocationStatus)">
              {{ getDetailStatusText(detail.allocationStatus) }}
            </a-tag>
          </template>

          <!-- 物料基本信息 -->
          <a-descriptions :column="2" size="small" bordered style="margin-bottom: 16px">
            <a-descriptions-item label="物料类型">
              <j-dict-tag v-if="detail.materialType" :value="detail.materialType" dictCode="material_type" />
              <span v-else>-</span>
            </a-descriptions-item>
            <a-descriptions-item label="物料编码">
              {{ detail.materialCode || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="物料名称">
              {{ detail.materialName || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="规格">
              {{ detail.specification || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="颜色">
              {{ detail.color || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="数量"> {{ detail.quantity || 0 }} {{ detail.unit || '' }} </a-descriptions-item>
            <a-descriptions-item label="已分配数量" v-if="detail.allocatedQuantity">
              <span style="color: #1890ff; font-weight: bold"
                >{{ detail.allocatedQuantity || 0 }} {{ detail.unit || '' }}</span
              >
            </a-descriptions-item>
            <a-descriptions-item label="剩余数量" v-if="detail.remainingQuantity">
              <span :style="{ color: detail.remainingQuantity > 0 ? '#ff4d4f' : '#52c41a', fontWeight: 'bold' }">
                {{ detail.remainingQuantity || 0 }} {{ detail.unit || '' }}
              </span>
            </a-descriptions-item>
          </a-descriptions>

          <!-- 出库方案详情 -->
          <div v-if="detail.allocationPlans && detail.allocationPlans.length > 0">
            <h4 style="margin-bottom: 12px">出库方案详情</h4>
            <a-table
              :columns="allocationColumns"
              :data-source="detail.allocationPlans"
              :pagination="false"
              size="small"
              bordered
              row-key="id"
            >
              <template slot="locationInfo" slot-scope="text, record">
                <div>
                  <div>
                    <strong>{{ record.warehouseName || '-' }}</strong>
                  </div>
                  <div style="color: #666; font-size: 12px">{{ record.locationName || '-' }}</div>
                  <div v-if="record.batchNo" style="color: #666; font-size: 12px">批次：{{ record.batchNo }}</div>
                </div>
              </template>

              <template slot="quantityInfo" slot-scope="text, record">
                <div>
                  <div>
                    分配：<strong style="color: #1890ff">{{ record.allocationQuantity || 0 }}</strong>
                    {{ record.unit || '' }}
                  </div>
                </div>
              </template>

              <template slot="allocationStatus" slot-scope="text">
                <a-tag :color="getAllocationStatusColor(text)">
                  {{ getAllocationStatusText(text) }}
                </a-tag>
              </template>

              <template slot="status" slot-scope="text">
                <a-tag :color="getOutboundStatusColor(text)">
                  {{ getOutboundStatusText(text) }}
                </a-tag>
              </template>
            </a-table>
          </div>

          <!-- 无分配方案且无剩余数量时 -->
          <div v-else>
            <a-empty description="暂无出库方案" size="small" />
          </div>

          <!-- 库存不足提示 -->
          <div v-if="detail.remainingQuantity && detail.remainingQuantity > 0">
            <a-alert
              message="库存不足"
              :description="`该物料库存不足，缺少 ${detail.remainingQuantity} ${
                detail.unit || ''
              }，请及时补充库存或创建采购单`"
              type="warning"
              show-icon
              style="margin-top: 12px"
            />
          </div>
        </a-collapse-panel>
      </a-collapse>

      <!-- 无明细数据时的提示 -->
      <a-empty v-else description="暂无明细信息" />

      <!-- 操作信息 -->
      <a-divider orientation="left">操作信息</a-divider>
      <a-descriptions bordered>
        <a-descriptions-item label="创建人">
          {{ outbound.createBy }}
        </a-descriptions-item>
        <a-descriptions-item label="创建时间">
          {{ outbound.createTime }}
        </a-descriptions-item>
        <a-descriptions-item label="更新人">
          {{ outbound.updateBy }}
        </a-descriptions-item>
        <a-descriptions-item label="更新时间">
          {{ outbound.updateTime }}
        </a-descriptions-item>
      </a-descriptions>

      <div class="drawer-footer" style="text-align: center; margin-top: 20px">
        <a-button @click="handlePrint" type="primary"> <a-icon type="printer" />打印 </a-button>
        <a-button @click="close" style="margin-left: 8px"> 关闭 </a-button>
      </div>
    </a-spin>
  </a-drawer>
</template>

<script>
import { getOutboundById } from '@/api/wms/outbound'
import JDictTag from '@/components/dict/JDictTag'
import { getAction } from '@/api/manage'

export default {
  name: 'OutboundDetail',
  components: {
    JDictTag,
  },
  data() {
    return {
      title: '详情',
      visible: false,
      confirmLoading: false,
      outbound: {},
      allocationColumns: [
        {
          title: '库位信息',
          dataIndex: 'locationInfo',
          width: 200,
          scopedSlots: { customRender: 'locationInfo' },
        },
        {
          title: '数量信息',
          dataIndex: 'quantityInfo',
          width: 150,
          scopedSlots: { customRender: 'quantityInfo' },
        },
        {
          title: '分配状态',
          dataIndex: 'allocationStatus',
          width: 100,
          scopedSlots: { customRender: 'allocationStatus' },
        },
        {
          title: '出库状态',
          dataIndex: 'status',
          width: 100,
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '备注',
          dataIndex: 'remark',
          ellipsis: true,
        },
      ],
    }
  },
  methods: {
    show(record) {
      this.visible = true
      this.outbound = {}
      this.loadDetail(record.id)
    },
    loadDetail(id) {
      this.confirmLoading = true
      getOutboundById({ id: id })
        .then((res) => {
          if (res.success) {
            this.outbound = res.result
            // 加载每个明细的出库方案
            this.loadAllocationPlans(id)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },

    // 加载出库方案详情
    loadAllocationPlans(outboundId) {
      getAction('/wms/outbound/getAllocationPlan', { outboundId })
        .then((res) => {
          if (res.success && res.result) {
            // 将分配方案按出库明细分组
            const allocationPlansMap = {}
            res.result.forEach((plan) => {
              const detailKey = `${plan.materialCode}_${plan.specification || ''}_${plan.color || ''}`
              if (!allocationPlansMap[detailKey]) {
                allocationPlansMap[detailKey] = []
              }
              allocationPlansMap[detailKey].push(plan)
            })

            // 将分配方案关联到对应的出库明细
            if (this.outbound.outboundDetailList) {
              this.outbound.outboundDetailList.forEach((detail, index) => {
                const detailKey = `${detail.materialCode}_${detail.specification || ''}_${detail.color || ''}`
                const allocationPlans = allocationPlansMap[detailKey] || []
                // 使用 $set 确保 Vue 能检测到属性变化
                this.$set(this.outbound.outboundDetailList[index], 'allocationPlans', allocationPlans)

                // 计算已分配数量和剩余数量
                const totalAllocated = allocationPlans.reduce((sum, plan) => sum + (plan.allocationQuantity || 0), 0)
                this.$set(this.outbound.outboundDetailList[index], 'allocatedQuantity', totalAllocated)
                this.$set(
                  this.outbound.outboundDetailList[index],
                  'remainingQuantity',
                  (detail.quantity || 0) - totalAllocated
                )

                // 设置分配状态
                let allocationStatus = '3' // 未分配
                if (totalAllocated > 0) {
                  allocationStatus = totalAllocated >= (detail.quantity || 0) ? '1' : '2' // 完全分配 : 部分分配
                }
                this.$set(this.outbound.outboundDetailList[index], 'allocationStatus', allocationStatus)
              })
            }
          }
        })
        .catch((err) => {
          console.error('加载出库方案失败:', err)
        })
    },

    // 获取物料标题
    getMaterialHeader(detail) {
      let header = `${detail.materialName || '未知物料'} (${detail.materialCode || ''})`
      if (detail.specification) {
        header += ` - ${detail.specification}`
      }
      if (detail.color) {
        header += ` - ${detail.color}`
      }
      header += ` | 需求: ${detail.quantity || 0} ${detail.unit || ''}`

      if (detail.allocatedQuantity) {
        header += `, 已分配: ${detail.allocatedQuantity} ${detail.unit || ''}`
      }

      if (detail.remainingQuantity && detail.remainingQuantity > 0) {
        header += `, 缺少: ${detail.remainingQuantity} ${detail.unit || ''}`
      }

      return header
    },

    // 获取明细状态颜色
    getDetailStatusColor(allocationStatus) {
      if (!allocationStatus) return 'default'
      const colorMap = {
        1: 'green', // 完全分配
        2: 'orange', // 部分分配
        3: 'red', // 未分配
      }
      return colorMap[allocationStatus] || 'default'
    },

    // 获取明细状态文本
    getDetailStatusText(allocationStatus) {
      if (!allocationStatus) return '未知状态'
      const textMap = {
        1: '完全分配',
        2: '部分分配',
        3: '未分配',
      }
      return textMap[allocationStatus] || '未知状态'
    },

    // 获取分配状态颜色
    getAllocationStatusColor(status) {
      const colorMap = {
        0: 'default', // 待分配
        1: 'green', // 已分配
        2: 'orange', // 部分分配
      }
      return colorMap[status] || 'default'
    },

    // 获取分配状态文本
    getAllocationStatusText(status) {
      const textMap = {
        0: '待分配',
        1: '已分配',
        2: '部分分配',
      }
      return textMap[status] || '未知'
    },

    // 获取出库状态颜色
    getOutboundStatusColor(status) {
      const colorMap = {
        0: 'red', // 待出库
        1: 'green', //已出库
      }
      return colorMap[status] || 'default'
    },

    // 获取出库状态文本
    getOutboundStatusText(status) {
      const textMap = {
        0: '待出库',
        1: '已出库',
      }
      return textMap[status] || '未知'
    },

    close() {
      this.visible = false
    },
    handlePrint() {
      this.$emit('print', this.outbound)
    },
    handleViewVoucher() {
      // 查看凭证
      if (this.outbound.outboundVoucher) {
        window.open(this.outbound.outboundVoucher)
      }
    },
  },
}
</script>

<style scoped>
</style> 